$(document).ready(function() {
    function fetchDataAndUpdate(globalName) {
        $.get(`http://127.0.0.1:5000/task3/marketName=${globalName}`).done(function (data) {
            var categories = data.index;
            var rawData = data.value;

            // 手动处理数据
            function calculateBoxplotData(data) {
                var sortedData = data.map(arr => arr.slice().sort((a, b) => a - b));
                var boxData = sortedData.map(arr => {
                    var min = arr[0];
                    var Q1 = quantile(arr, 0.25);
                    var median = quantile(arr, 0.5);
                    var Q3 = quantile(arr, 0.75);
                    var max = arr[arr.length - 1];
                    return [min, Q1, median, Q3, max];
                });

                var outliers = [];
                sortedData.forEach((arr, idx) => {
                    var Q1 = boxData[idx][1];
                    var Q3 = boxData[idx][3];
                    var IQR = Q3 - Q1;
                    var lowerFence = Q1 - 1.5 * IQR;
                    var upperFence = Q3 + 1.5 * IQR;
                    arr.forEach(val => {
                        if (val < lowerFence || val > upperFence) {
                            outliers.push([idx, val]);
                        }
                    });
                });

                return { boxData, outliers };
            }

            function quantile(arr, q) {
                var pos = (arr.length - 1) * q;
                var base = Math.floor(pos);
                var rest = pos - base;
                if ((arr[base + 1] !== undefined)) {
                    return arr[base] + rest * (arr[base + 1] - arr[base]);
                } else {
                    return arr[base];
                }
            }

            var processedData = calculateBoxplotData(rawData);

            var myeCharts = echarts.init(document.querySelector('.panel .bar3'));
            var option = {
                title: {
                    text: "卖场销售预算",
                    x: "center",
                    y: "2%",
                    textStyle: {
                        color: '#fff',
                        fontSize: '15'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    top: '20%',
                    left: '10%',
                    right: '10%',
                    bottom: '20%'
                },
                xAxis: {
                    type: 'category',
                    data: categories,
                    nameGap: 20,
                    axisLabel: {
                        rotate: 35,
                        fontSize: 10,
                        color: '#fff'
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLabel:{
                        color: '#fff'
                    },
                    splitArea: {
                        show: true
                    }
                },
                series: [
                    {
                        name: '卖场数据',
                        type: 'boxplot',
                        data: processedData.boxData,
                        tooltip: {
                            formatter: function (param) {
                                return [
                                    '类别 ' + categories[param.dataIndex] + ': ',
                                    '最大值: ' + param.data[4],
                                    '第三四分位数: ' + param.data[3],
                                    '中位数: ' + param.data[2],
                                    '第一四分位数: ' + param.data[1],
                                    '最小值: ' + param.data[0]
                                ].join('<br/>');
                            }
                        },
                        itemStyle: {
                            color: {
                                type: 'linear',
                                x: 0, // 渐变起点：左
                                y: 0, // 渐变起点：上
                                x2: 0, // 渐变终点：右
                                y2: 1, // 渐变终点：下
                                colorStops: [
                                    {
                                        offset: 0, color: '#ccccff' // 起始颜色
                                    },
                                    {
                                        offset: 1, color: '#aeefff' // 结束颜色
                                    }
                                ],
                                global: false // 使用局部坐标系
                            }
                        }
                    },
                    {
                        name: 'outlier',
                        type: 'scatter',
                        data: processedData.outliers
                    }
                ]
            };

            myeCharts.setOption(option);
        });
    }
    fetchDataAndUpdate(window.globalName)
    $(document).on('globalNameChanged', function(event, globalName) {
        fetchDataAndUpdate(window.globalName)
    })
})
